/*
 * @Author: Await
 * @Date: 2025-05-06 17:00:35
 * @LastEditors: Await
 * @LastEditTime: 2025-05-06 20:35:00
 * @Description: 主题构建器组件
 */
import React, { useState, useEffect } from 'react';
import {
  Tabs,
  Button,
  Space,
  message,
  Typography,
  Modal,
  Input,
  Tooltip,
  Card,
  Row,
  Col,
  Radio,
  Divider
} from 'antd';
import type { TabsProps } from 'antd';
import {
  DownloadOutlined,
  ImportOutlined,
  ExportOutlined,
  QuestionCircleOutlined,
  ReloadOutlined,
  UndoOutlined
} from '@ant-design/icons';
import type { ThemeConfig } from '../../../types/chartTypes';
import BasicConfig from './BasicConfig';
import VisualMapConfig from './VisualMapConfig';
import AxisConfig from './AxisConfig';
import LegendConfig from './LegendConfig';
import ToolboxConfig from './ToolboxConfig';
import TooltipConfig from './TooltipConfig';
import TimelineConfig from './TimelineConfig';
import SeriesConfig from './SeriesConfig';
import defaultTheme from './presets/default';
import { presetThemes, presetThemeNames, presetThemePreviews } from './presets';

const { Title } = Typography;

// 使用从presets导入的默认主题
const defaultThemeConfig = defaultTheme;

interface ThemeBuilderProps {
  value?: ThemeConfig;
  onChange?: (value: ThemeConfig) => void;
}

/**
 * ECharts主题构建器组件
 * 基于官方主题构建工具 https://echarts.apache.org/zh/theme-builder.html
 */
const ThemeBuilder: React.FC<ThemeBuilderProps> = ({ value, onChange }) => {
  // 使用内部状态管理主题配置
  const [themeConfig, setThemeConfig] = useState<ThemeConfig>(value || defaultThemeConfig);
  const [themeNameModalVisible, setThemeNameModalVisible] = useState(false);
  const [themeName, setThemeName] = useState(themeConfig.themeName || '自定义主题');
  const [importModalVisible, setImportModalVisible] = useState(false);
  const [importConfigJson, setImportConfigJson] = useState('');
  const [activeTab, setActiveTab] = useState('presets'); // 默认显示预设主题页
  const [presetThemeModalVisible, setPresetThemeModalVisible] = useState(false);
  const [selectedPresetTheme, setSelectedPresetTheme] = useState('default');

  // 当外部value变化时，更新内部状态
  useEffect(() => {
    if (value) {
      setThemeConfig(value);
      setThemeName(value.themeName || '自定义主题');
    }
  }, [value]);

  // 处理主题配置变更
  const handleConfigChange = (key: string, newConfig: any) => {
    const updatedConfig = {
      ...themeConfig,
      [key]: newConfig,
    };
    setThemeConfig(updatedConfig);
    onChange?.(updatedConfig);
  };

  // 保存主题名称
  const saveThemeName = () => {
    const updatedConfig = {
      ...themeConfig,
      themeName,
    };
    setThemeConfig(updatedConfig);
    onChange?.(updatedConfig);
    setThemeNameModalVisible(false);
  };

  // 处理导入配置
  const handleImportConfig = () => {
    try {
      const importedConfig = JSON.parse(importConfigJson);
      setThemeConfig(importedConfig);
      onChange?.(importedConfig);
      setImportModalVisible(false);
      message.success('配置导入成功');
    } catch (error) {
      message.error('配置格式错误，请检查JSON格式');
    }
  };

  // 处理预设主题选择
  const handlePresetThemeSelect = (themeKey: string) => {
    setSelectedPresetTheme(themeKey);
  };

  // 应用选中的预设主题
  const applyPresetTheme = () => {
    const selectedTheme = presetThemes[selectedPresetTheme];
    if (selectedTheme) {
      // 确保主题有名称
      const themeName = selectedTheme.themeName || presetThemeNames[selectedPresetTheme];
      
      // 创建主题完整配置，确保所有必要属性都存在
      const completeTheme = {
        ...selectedTheme,
        themeName: themeName,
        // 确保以下必要属性存在
        backgroundColor: selectedTheme.backgroundColor || '#ffffff',
        color: selectedTheme.color || ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
        textStyle: selectedTheme.textStyle || { color: '#333333' }
      };
      
      // 更新本地状态
      setThemeConfig(completeTheme);
      setThemeName(themeName);
      
      // 调用onChange回调以触发主题更新
      onChange?.(completeTheme);
      
      // 关闭模态框并显示成功消息
      setPresetThemeModalVisible(false);
      message.success(`已应用"${themeName}"主题`);
    }
  };

  // 打开预设主题选择模态框
  const openPresetThemeModal = () => {
    setPresetThemeModalVisible(true);
  };

  // 导出配置为JSON
  const exportConfigAsJson = () => {
    const dataStr = JSON.stringify(themeConfig, null, 2);
    const dataUri = 'data:application/json;charset=utf-8,' + encodeURIComponent(dataStr);
    const exportFileName = `${themeConfig.themeName || 'echarts-theme'}.json`;

    const linkElement = document.createElement('a');
    linkElement.setAttribute('href', dataUri);
    linkElement.setAttribute('download', exportFileName);
    linkElement.click();
  };

  // 导出为JS主题文件
  const exportAsThemeJs = () => {
    const themeNameVar = (themeConfig.themeName || 'customTheme').replace(/\s+/g, '');
    const jsContent = `(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['exports', 'echarts'], factory);
    } else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
        // CommonJS
        factory(exports, require('echarts'));
    } else {
        // Browser globals
        factory({}, root.echarts);
    }
}(this, function (exports, echarts) {
    var log = function (msg) {
        if (typeof console !== 'undefined') {
            console && console.error && console.error(msg);
        }
    };
    if (!echarts) {
        log('ECharts is not Loaded');
        return;
    }
    echarts.registerTheme('${themeNameVar}', ${JSON.stringify(themeConfig, null, 2)});
}));`;

    const dataUri = 'data:text/javascript;charset=utf-8,' + encodeURIComponent(jsContent);
    const exportFileName = `${themeNameVar}.js`;

    const linkElement = document.createElement('a');
    linkElement.setAttribute('href', dataUri);
    linkElement.setAttribute('download', exportFileName);
    linkElement.click();
  };

  // 重置为默认配置
  const resetToDefault = () => {
    setThemeConfig(defaultThemeConfig);
    onChange?.(defaultThemeConfig);
    message.success('已重置为默认主题配置');
  };

  // 渲染预设主题选择模态框
  const renderPresetThemeModal = () => (
    <Modal
      title="选择预设主题"
      open={presetThemeModalVisible}
      onOk={applyPresetTheme}
      onCancel={() => setPresetThemeModalVisible(false)}
      width={800}
      okText="应用主题"
      cancelText="取消"
    >
      <Radio.Group 
        onChange={(e) => handlePresetThemeSelect(e.target.value)} 
        value={selectedPresetTheme}
        style={{ width: '100%' }}
      >
        <Row gutter={[16, 16]}>
          {Object.keys(presetThemes).map((themeKey) => (
            <Col span={6} key={themeKey}>
              <Radio.Button 
                value={themeKey} 
                style={{ 
                  width: '100%', 
                  height: 'auto', 
                  padding: 0, 
                  margin: 0, 
                  display: 'block', 
                  border: themeKey === selectedPresetTheme ? '2px solid #1890ff' : '1px solid #d9d9d9',
                  borderRadius: '4px',
                  overflow: 'hidden'
                }}
              >
                <div style={{ textAlign: 'center', padding: '8px 0' }}>
                  <div style={{ height: 120, overflow: 'hidden', marginBottom: 10 }}>
                    <img 
                      src={presetThemePreviews[themeKey]} 
                      alt={presetThemeNames[themeKey]} 
                      style={{ 
                        width: '100%', 
                        height: 'auto',
                        background: themeKey === 'dark' || themeKey === 'chalk' ? '#333' : 'transparent'
                      }} 
                    />
                  </div>
                  <div style={{ textAlign: 'center', padding: '0 10px 8px' }}>
                    {presetThemeNames[themeKey]}
                  </div>
                </div>
              </Radio.Button>
            </Col>
          ))}
        </Row>
      </Radio.Group>
      
      <Divider>预览信息</Divider>
      
      <div style={{ marginTop: 16 }}>
        <Row gutter={16}>
          <Col span={12}>
            <Card title="颜色列表" size="small">
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {presetThemes[selectedPresetTheme]?.color?.map((color, index) => (
                  <div 
                    key={index} 
                    style={{
                      backgroundColor: color,
                      width: 24,
                      height: 24,
                      borderRadius: 4,
                      border: '1px solid #ddd'
                    }}
                    title={color}
                  />
                ))}
              </div>
            </Card>
          </Col>
          <Col span={12}>
            <Card title="基本信息" size="small">
              <p><strong>主题名称:</strong> {presetThemeNames[selectedPresetTheme]}</p>
              <p><strong>背景色:</strong> {presetThemes[selectedPresetTheme]?.backgroundColor}</p>
              <p><strong>文本颜色:</strong> {presetThemes[selectedPresetTheme]?.textStyle?.color}</p>
            </Card>
          </Col>
        </Row>
      </div>
    </Modal>
  );

  // 渲染预设主题选择标签页
  const renderPresetsTab = () => (
    <div style={{ padding: '16px 0' }}>
      <Title level={5}>预设主题</Title>
      <Typography.Paragraph>
        选择一个预设主题作为基础，您可以在应用后进一步自定义。
      </Typography.Paragraph>
      
      <Button 
        type="primary" 
        onClick={openPresetThemeModal}
        style={{ marginBottom: 16 }}
      >
        选择预设主题
      </Button>
      
      <Card title="当前主题预览" size="small">
        <Row gutter={16}>
          <Col span={18}>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 16 }}>
              {themeConfig?.color?.map((color, index) => (
                <div 
                  key={index} 
                  style={{
                    backgroundColor: color,
                    width: 24,
                    height: 24,
                    borderRadius: 4,
                    border: '1px solid #ddd'
                  }}
                  title={color}
                />
              ))}
            </div>
            
            <Row gutter={16}>
              <Col span={12}>
                <p><strong>背景色:</strong> {themeConfig?.backgroundColor}</p>
                <p><strong>文本颜色:</strong> {themeConfig?.textStyle?.color}</p>
              </Col>
              <Col span={12}>
                <p><strong>标题颜色:</strong> {themeConfig?.title?.textStyle?.color}</p>
                <p><strong>坐标轴颜色:</strong> {themeConfig?.axis?.axisLine?.lineStyle?.color}</p>
              </Col>
            </Row>
          </Col>
        </Row>
      </Card>
    </div>
  );

  // 定义标签页配置
  const tabItems: TabsProps['items'] = [
    {
      key: 'presets',
      label: '预设主题',
      children: renderPresetsTab(),
    },
    {
      key: 'basic',
      label: '基本配置',
      children: <BasicConfig 
        value={themeConfig} 
        onChange={(config) => handleConfigChange('basic', config)} 
      />,
    },
    {
      key: 'visualMap',
      label: '视觉映射',
      children: <VisualMapConfig 
        value={themeConfig} 
        onChange={(config) => handleConfigChange('visualMap', config)} 
      />,
    },
    {
      key: 'axis',
      label: '坐标轴',
      children: <AxisConfig 
        value={themeConfig} 
        onChange={(config) => handleConfigChange('axis', config)} 
      />,
    },
    {
      key: 'legend',
      label: '图例',
      children: <LegendConfig 
        value={themeConfig} 
        onChange={(config) => handleConfigChange('legend', config)} 
      />,
    },
    {
      key: 'toolbox',
      label: '工具箱',
      children: <ToolboxConfig 
        value={themeConfig} 
        onChange={(config) => handleConfigChange('toolbox', config)} 
      />,
    },
    {
      key: 'tooltip',
      label: '提示框',
      children: <TooltipConfig 
        value={themeConfig} 
        onChange={(config) => handleConfigChange('tooltip', config)} 
      />,
    },
    {
      key: 'timeline',
      label: '时间轴',
      children: <TimelineConfig 
        value={themeConfig} 
        onChange={(config) => handleConfigChange('timeline', config)} 
      />,
    },
    {
      key: 'series',
      label: '系列',
      children: <SeriesConfig 
        value={themeConfig} 
        onChange={(config) => handleConfigChange('series', config)} 
      />,
    },
  ];

  return (
    <div className="theme-builder">
      <div className="theme-builder-header" style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Title level={4} style={{ margin: 0 }}>
          {themeConfig.themeName || '自定义主题'}
          <Tooltip title="修改主题名称">
            <Button
              type="text"
              icon={<QuestionCircleOutlined />}
              size="small"
              onClick={() => setThemeNameModalVisible(true)}
              style={{ marginLeft: 8 }}
            />
          </Tooltip>
        </Title>
        <Space>
          <Button
            icon={<ImportOutlined />}
            onClick={() => setImportModalVisible(true)}
          >
            导入配置
          </Button>
          <Button
            icon={<ExportOutlined />}
            onClick={exportConfigAsJson}
          >
            导出配置
          </Button>
          <Button
            type="primary"
            icon={<DownloadOutlined />}
            onClick={exportAsThemeJs}
          >
            下载主题
          </Button>
          <Button
            icon={<ReloadOutlined />}
            onClick={resetToDefault}
          >
            刷新
          </Button>
          <Button
            icon={<UndoOutlined />}
            onClick={resetToDefault}
          >
            复原
          </Button>
        </Space>
      </div>

      <Card>
        <Tabs 
          activeKey={activeTab} 
          onChange={setActiveTab}
          items={tabItems}
        />
      </Card>

      <Modal
        title="修改主题名称"
        open={themeNameModalVisible}
        onOk={saveThemeName}
        onCancel={() => setThemeNameModalVisible(false)}
      >
        <Input
          placeholder="请输入主题名称"
          value={themeName}
          onChange={(e) => setThemeName(e.target.value)}
        />
      </Modal>

      <Modal
        title="导入主题配置"
        open={importModalVisible}
        onOk={handleImportConfig}
        onCancel={() => setImportModalVisible(false)}
        width={600}
      >
        <Typography.Paragraph>
          请粘贴JSON格式的主题配置:
        </Typography.Paragraph>
        <Input.TextArea
          rows={10}
          value={importConfigJson}
          onChange={(e) => setImportConfigJson(e.target.value)}
          placeholder="粘贴JSON主题配置..."
        />
      </Modal>
      
      {renderPresetThemeModal()}
    </div>
  );
};

export default ThemeBuilder;